import axios from 'axios';
import qs from 'qs';
import router from '@/router';
import {Dialog} from 'vant';


axios.defaults.timeout = 5000;
axios.defaults.baseURL = '';
var token = '';
function Token() {
  if(localStorage.getItem('toketn') == undefined){
    token =''
  }else{
    let tokens = localStorage.getItem('toketn')
    token = JSON.parse(tokens).token
  }
}
  




// http request 拦截器(请求之前拦截)
axios.interceptors.request.use(
    config => {
      Token()
        config.headers["request-source"] = 'h5';
        if (token) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
);

//http response 拦截器
axios.interceptors.response.use(
  response => {
    console.log(response.data)
    if(response.data.code==601){
      Dialog.alert({
        title: '提示',
        message: '您的登录已过期，请重新登录'
      }).then(() => {
        router.push('/')
      });
    }else{
      if(response.data.code==200){
        }else{
          Dialog.alert({
            title: '提示',
            message: response.data.message
          }).then(() => {
          });
        }
    }
    return response;            

  },
  error => {
    return Promise.reject(error)
  }
)


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        })
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err)
            })
    })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.post(url, qs.stringify(data))
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err)
            })
    })
}


/**
 *  post  请求方式
 *
 */
// var logintext={
//   username:'zhanghua',
//   password:'123456',
// }
// this.$post(urlConfig.login,logintext)
//   .then(res => {
//   console.log(res);
// })


/**
*  get  请求方式
*
*/
// this.$get(urlConfig.friendList)
//   .then(res => {
//   console.log(res);
// })
